package com.ce.study.procum;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author Administrator
 * HashMap不是线程安全的
 * ConcurrentHashMap是线程安全的
 */
public class TestUnSynMap {
	//在使用hashmap时,游历和remove一起操作时会报异常，java.util.ConcurrentModificationException
	public Map<String, Integer> map = new HashMap<String, Integer>();
	
	//ConcurrentHashMap是线程安全的
	//public ConcurrentMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TestUnSynMap synInt = new TestUnSynMap();
		PutThread putTh = synInt.new PutThread();
		putTh.start();
		
		RemoveThread removeTh = synInt.new RemoveThread();
		removeTh.start();
		
		ForThread forTh = synInt.new ForThread();
		forTh.start();
		
	}

	public class PutThread extends Thread {
		@Override
		public void run() {
			while(true) {
				try {
					map.put("key", 10);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public class RemoveThread extends Thread {
		@Override
		public void run() {
			while(true) {
				try {
					map.remove("key");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public class ForThread extends Thread {
		@Override
		public void run() {
			while(true) {
				try {
					for (Iterator<String> j = map.keySet().iterator(); j.hasNext();) {
						String key = j.next();
						System.out.println(key);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
